local PartnerRelationPanel = app.mvc.createPanelClass(...)
local PartnerHelper = require("app.partner.PartnerHelper")
local PartnerRelationRender = import(".renders.PartnerRelationRender")
--data =
function PartnerRelationPanel.createWithData(data, node)
    local sprite = PartnerRelationPanel.extend(node or cc.CSLoader:createNode(Res.PartnerRelationPanel))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end


function PartnerRelationPanel.create(node)
    return PartnerRelationPanel.createWithData(nil, node)
end

function PartnerRelationPanel:init(data)
    self.super.init(self, data)
    self._data = PartnerHelper.createRelationData()


    local sp = cc.Sprite:createWithSpriteFrameName(Res.PartnerLevelProgressPath)

    self._progressTime = cc.ProgressTimer:create( sp )
    self._progressTime:setType( cc.PROGRESS_TIMER_TYPE_RADIAL )
    self._progressTime:setMidpoint(display.ANCHOR_POINTS[1])
    self._progressTime:setAnchorPoint(0,0)
    self._ui["Panel_r/Panel_2/Panel_exp"]:addChild(self._progressTime)


    self._ui["Panel_r/Panel_2/btn_q"]:setTouchEnabled(true)
    self._ui["Panel_r/Panel_2/btn_q"]:addClickEventListener(function(sender)
        local params = {}
        params.tipsType = Enums.TipsType.contents
        params.contents = self:_getTipsParams()
        local otherParams = {}
        local size = sender:getContentSize()
        local pos = sender:convertToWorldSpace(cc.p(0,0))
        otherParams.tipPos = cc.p(pos.x - size.width/2, pos.y + size.height)
        EM:notify(ViewEvent.Partner_ShowTips, params, otherParams)
    end)

    self._ui["Panel_r/Panel_1/tlt"]:setString(L("ui_csd_734"))

    self:initUI()
    self._curSelectIndex = 0
    self:onTabClick(1)
    self:registerViewEvent({
        {name = ViewEvent.Partner_DataChange, callback = handler(self, self.updateData)},
    })
end


function PartnerRelationPanel:_getTipsParams()
    if not self._data then
        return {}
    end
    local curData = self._data[self._curSelectIndex]
    local relations = curData.relations
   
    local contents = {}
    local part1 = {}

    local colorNormal = cc.c3b(255, 225, 132)
    local colorGreen = cc.c3b(0, 220, 220)
    local colorGray = cc.c3b(160, 160, 160)
    -- PartnerRelationScoreTipTitle = "升级羁绊点品质以提升羁绊评级"
    table.insert(part1, {text = L("PartnerRelationScoreTipTitle2"), color = colorNormal})
    table.insert(part1, {text = "", color = colorNormal})
    -- PartnerRelationScoreStr = "%s羁绊点 %s分"

    for k ,v in pairs(PartnerHelper.getRelationScoreConfig()) do
        table.insert(part1, {
            text = string.format(L("PartnerRelationScoreStr"), PartnerHelper.getPartnerRelationColorStringByQuality(k), v),
            color = PartnerHelper.getPartnerRelationColorByQuality(k)
        })
    end
    table.insert(part1, {text = "", color = colorNormal})

    local totalScore = 0
    for k, v in pairs(relations) do
        totalScore = totalScore + v:getScore()
    end
    local scoreConfig, nextScoreConfig = PartnerHelper.getPartnerRelationLevelByTotalScore(totalScore)
    if nextScoreConfig then
        -- PartnerRelationScoreTipTitle = "下一个羁绊评级：%s"
        table.insert(part1, {text = string.format(L("PartnerRelationScoreTipTitle"), nextScoreConfig.name), color = colorNormal})
        local busterName, busterValue  = GD:getPropShowData(curData.propId, nextScoreConfig.buster)
        table.insert(part1, {text = string.format(L("partnerBusterUpgradetips1"), busterName or "", busterValue or 0), color = colorNormal})
    end
    
    table.insert(contents, part1)
    return contents
end

function PartnerRelationPanel:updateData()
    self._data = PartnerHelper.createRelationData()
    self:refresh()
end

function PartnerRelationPanel:refresh()
    self:_updateRelation()
    self:_updateRightPanel()
end

function PartnerRelationPanel:initUI()
    local chooseImgs = {}
    local relationrRenders = {}
    for i =1, 4 do
        local name = self._data[i].name
        
        local parentNode = self._ui["Panel/Panel_tab/btn_"..i]
        local panel = parentNode:findChild("Panel")
        panel:setTouchEnabled(true)
        local nameNode = panel:findChild("tlt")
        local iconNode = panel:findChild("icon")
        nameNode:setString(name)
        iconNode:loadTexture(Res.PartnerRelationPath..self._data[i].icon)

        chooseImgs[i] = panel:findChild("choose")
        panel:addClickEventListener(function()
            self:onTabClick(i)
        end)

        local parentNode = self._ui["Panel/fetter_"..i]
        local relationrRender = PartnerRelationRender.create(parentNode)
        relationrRender:setVisible(false)
        relationrRenders[i] = relationrRender
    end
    self._chooseImgs = chooseImgs
    self._relationrRenders = relationrRenders
end

function PartnerRelationPanel:onTabClick(index)
    if self._curSelectIndex == index then
        return
    end
    if self._chooseImgs[self._curSelectIndex] then
        self._chooseImgs[self._curSelectIndex]:setVisible(false)
    end
    if self._relationrRenders[self._curSelectIndex] then
        self._relationrRenders[self._curSelectIndex]:setVisible(false)
    end
    self._curSelectIndex = index
    self._chooseImgs[index]:setVisible(true)
    self._relationrRenders[index]:setVisible(true)
    
    self:_updateRelation()
    self:_updateRightPanel()
end


function PartnerRelationPanel:_updateRelation()
    local curData = self._data[self._curSelectIndex]
    self._relationrRenders[self._curSelectIndex]:setData(curData)
end

function PartnerRelationPanel:_updateRightPanel()
    local curData = self._data[self._curSelectIndex]
    local relations = curData.relations

    local allProps = {}
    local propsMap = {}
    local index = 0

    local totalScore = 0
    --此处要改为所有获得的随从身上添加的属性之和

    local allPartners = curData.partners
    for k,v in pairs(allPartners) do
        if v:isHave() then
            local props = v:getShowPlayerProps()
            for _, p in pairs(props) do
                if not propsMap[p[1]] then
                    index = index + 1
                    propsMap[p[1]] = index
                    allProps[index] = {id = p[1], value = 0}
                end
                allProps[propsMap[p[1]]].value = allProps[propsMap[p[1]]].value + p[2]
            end
        end
    end

    --但是评分还是羁绊的品质决定的
    for k, v in pairs(relations) do
        totalScore = totalScore + v:getScore()
    end

    local isNoHaveProps = true

    for i = 1, 3 do
        local parentNode = self._ui["Panel_r/Panel_1/data_"..i]
        local prop = allProps[i]
        if prop then
            local name, value = GD:getPropShowDataAndHandlerColon(prop.id, prop.value)
            parentNode:setVisible(true)
            local t = parentNode:findChild("tlt_data")
            t:setString(string.format(("%s%s"),name,value))
            isNoHaveProps = false
        else
          
            parentNode:setVisible(false)
        end
    end

    if #allProps == 0 then
        --不加属性的时候
        self._ui["Panel_r/Panel_1/tips_1"]:setVisible(true)
        self._ui["Panel_r/Panel_1/tips_1"]:setString(L("partnerString3"))
    else
        self._ui["Panel_r/Panel_1/tips_1"]:setVisible(false)
    end


    local scoreConfig, nextConfig = PartnerHelper.getPartnerRelationLevelByTotalScore(totalScore)
    if not nextConfig then
        nextConfig = scoreConfig
    end
    self._ui["Panel_r/Panel_2/tlt"]:setString(L("PartnerRelationScoreString"))
    self._ui["Panel_r/Panel_2/Panel_exp/icon"]:loadTexture(string.format("art/partner/%s.png",scoreConfig.name))

    self._ui["Panel_r/Panel_2/Panel_exp/exp_num"]:setString(string.format("%s/%s", totalScore, nextConfig.score))

    local percent = totalScore * 100/nextConfig.score
    if percent >= 100 then
        percent = 100
    end
    self._progressTime:setPercentage(percent)
    local busterName, busterValue  = GD:getPropShowData(curData.propId, scoreConfig.buster)
    if isNoHaveProps then
        self._ui["Panel_r/Panel_2/tips_1"]:setVisible(true)
        self._ui["Panel_r/Panel_2/tips"]:setVisible(false)
        self._ui["Panel_r/Panel_2/tips_1"]:setString(L("partnerString4"))
    else
        self._ui["Panel_r/Panel_2/tips_1"]:setVisible(false)
        self._ui["Panel_r/Panel_2/tips"]:setVisible(true)
        self._ui["Panel_r/Panel_2/tips"]:setString(string.format(L("partnerBusterUpgradetips1"), busterName or "", busterValue or 0))
    end
  
    --self._ui["Panel_r/bg_icon"]:loadTexture(Res.PartnerRelationPath..curData.bg)
end


return PartnerRelationPanel